package com.googlecode.felicalib.sample.applet;

import javax.swing.JApplet;

import com.googlecode.felicalib.sample.Felica;
import com.googlecode.felicalib.sample.client.FelicaTray;
import com.googlecode.felicalib.sample.polling.FelicaPollingHost;

/**
 * @author o.tanaka
 */
public class FelicaHeadlessApplet extends JApplet {

    /**
     * long serialVersionUID
     */
    private static final long serialVersionUID = 8056443327160508542L;
    private FelicaTray tray;

    private static final String APPLET_NAME = "FelicaHeadlessApplet";

    /**
     * @see java.applet.Applet#destroy()
     */
    @Override
    public void destroy() {
        FelicaPollingHost.polling(
                this.tray.getFelica(), Felica.WILDCARD,
                FelicaTray.NOT_POLLING);
        this.tray.getFelica().close();
        this.tray.getSystemTray().remove(
                this.tray.getTrayicon());
        this.tray = null;
    }

    /**
     * @return appletName
     */
    public final String getAppletName() {
        return FelicaHeadlessApplet.APPLET_NAME;
    }

    /**
     * @param aServiceCode
     *            serviceCode
     * @param anAddr
     *            addr
     * @return data
     */
    public String getData(final int aServiceCode, final int anAddr) {
        return this.tray.getData(aServiceCode, anAddr);
    }

    /**
     * @return idm
     */
    public String getIDm() {
        return this.tray.getIDm();
    }

    /**
     * @return pmm
     */
    public String getPMm() {
        return this.tray.getPMm();
    }

    /**
     * @see java.applet.Applet#init()
     */
    @Override
    public void init() {
        this.tray = new FelicaTray();
    }

    /**
     * @param aServiceCode
     *            serviceCode
     * @param anAddr
     *            addr
     * @param aData
     *            data
     * @return boolean true/false
     */
    public boolean setCard(
            final int aServiceCode,
            final int anAddr,
            final String aData) {
        final byte[] b = new byte[16];
        if (aData.length() <= 16) {
            for (int i = 0; i < aData.length(); i++) {
                b[i] = (byte) aData.charAt(i);
            }
        }
        return this.tray.setCard(aServiceCode, anAddr, b);
    }

}
